package com.iespring.service.app.order;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iespring.bean.admin.order.pojo.Order;
import com.iespring.bean.admin.order.pojo.OrderExample;
import com.iespring.bean.admin.order.pojo.OrderGoods;
import com.iespring.bean.admin.order.pojo.OrderGoodsExample;
import com.iespring.bean.admin.promotion.po.MallCoupon;
import com.iespring.bean.app.address.po.AddressPo;
import com.iespring.bean.app.aftersale.pojo.Aftersale;
import com.iespring.bean.app.cart.pojo.Cart;
import com.iespring.bean.app.cart.pojo.CartExample;
import com.iespring.bean.app.comment.pojo.Comment;
import com.iespring.bean.app.coupon.pojo.CouponUser;
import com.iespring.bean.app.coupon.pojo.CouponUserExample;
import com.iespring.bean.app.order.bo.CommentBO;
import com.iespring.bean.app.order.bo.OrderSubmitBO;
import com.iespring.bean.app.order.vo.*;
import com.iespring.bean.common.BaseParam;
import com.iespring.bean.common.CommonData;
import com.iespring.mapper.admin.*;
import com.iespring.mapper.app.AftersaleMapper;
import com.iespring.mapper.app.MarketCouponUserMapper;
import com.iespring.mapper.app.OrderUseCartMapper;
import com.iespring.util.UserInfoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: 浩澄
 * @Date: 2022/12/31-16:49
 * @Mission: #
 */
@Service
public class WxOrderServiceImpl implements WxOrderService {

    @Autowired
    PromotionOrderMapper orderMapper;

    @Autowired
    PromotionOrderGoodsMapper orderGoodsMapper;

    @Autowired
    MallAddressMapper addressMapper;

    @Autowired
    AftersaleMapper aftersaleMapper;

    @Autowired
    MallCommentMapper commentMapper;

    @Autowired
    OrderUseCartMapper cartMapper;

    @Autowired
    MallCouponMapper couponMapper;

    @Autowired
    MallSystemMapper systemMapper;

    @Autowired
    MarketCouponUserMapper couponUserMapper;

    @Override
    public CommonData list(BaseParam baseParam, Integer showType) {

        PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());

        OrderExample orderExample = new OrderExample();

        OrderExample.Criteria criteria = orderExample.createCriteria();

        //showType 0,1,2,3,4 对应all,101未付款,201已付款,301已发货, 401 402 用户,系统收货

        if (showType == 0) {

            ArrayList<Short> shortList = new ArrayList<>();

            shortList.add((short) 101);
            shortList.add((short) 102);
            shortList.add((short) 103);
            shortList.add((short) 201);
            shortList.add((short) 202);
            shortList.add((short) 203);
            shortList.add((short) 301);
            shortList.add((short) 401);
            shortList.add((short) 402);
            criteria.andOrderStatusIn(shortList);

        } else if (showType == 1) {

            criteria.andOrderStatusEqualTo((short) 101);
        } else if (showType == 2) {

            criteria.andOrderStatusEqualTo((short) 201);
        } else if (showType == 3) {

            criteria.andOrderStatusEqualTo((short) 301);
        } else if (showType == 4) {

            ArrayList<Short> shortList1 = new ArrayList<>();
            shortList1.add((short) 401);
            shortList1.add((short) 402);
            criteria.andOrderStatusIn(shortList1);

        }

        //删除的订单不查询
        criteria.andDeletedEqualTo(false);

        //根据userId查询(new)
        Integer userId = UserInfoUtils.getUser().getId();
        criteria.andUserIdEqualTo(userId);

        orderExample.setOrderByClause("add_time" + " " + "desc");

        //订单信息
        List<Order> orders = orderMapper.selectByExample(orderExample);

        //封装到OrderListVO
        ArrayList<OrderListVO> orderListVOS = new ArrayList<>();

        for (Order order : orders) {

            OrderListVO orderListVO = new OrderListVO();

            orderListVO.setIsGroupin(false);

            HandleOptionVO handleOptionVO = new HandleOptionVO();

            //订单的商品信息
            OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
            orderGoodsExample.createCriteria().andOrderIdEqualTo(order.getId());
            List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);

            //封装到OrderListVO的goodsList
            orderListVO.setGoodsList(orderGoods);

            orderListVO.setAftersaleStatus(order.getAftersaleStatus());
            orderListVO.setOrderSn(order.getOrderSn());
            orderListVO.setActualPrice(order.getActualPrice());
            orderListVO.setId(order.getId());

            if (order.getOrderStatus() == 101){
                orderListVO.setOrderStatusText("未付款");

                //封装到orderListVO的handleOption
                handleOptionVO.setCancel(true);
                handleOptionVO.setPay(true);

            }else if (order.getOrderStatus() == 102){

                orderListVO.setOrderStatusText("已取消");
                handleOptionVO.setDelete(true);

            }else if (order.getOrderStatus() == 103){

                orderListVO.setOrderStatusText("系统已取消");
                handleOptionVO.setDelete(true);

            }else if (order.getOrderStatus() == 201){

                orderListVO.setOrderStatusText("已付款");
                handleOptionVO.setRefund(true);

            }else if (order.getOrderStatus() == 202){

                orderListVO.setOrderStatusText("申请退款");

            }else if (order.getOrderStatus() == 203){

                orderListVO.setOrderStatusText("已退款");

            }else if (order.getOrderStatus() == 301){

                orderListVO.setOrderStatusText("已发货");
                handleOptionVO.setConfirm(true);

            }else if (order.getOrderStatus() == 401){

                orderListVO.setOrderStatusText("已收货");
                handleOptionVO.setDelete(true);
                handleOptionVO.setComment(true);
                handleOptionVO.setRebuy(true);
                handleOptionVO.setAftersale(true);

            }else if (order.getOrderStatus() == 402){

                orderListVO.setOrderStatusText("系统已收货");
                handleOptionVO.setDelete(true);
                handleOptionVO.setComment(true);
                handleOptionVO.setRebuy(true);
                handleOptionVO.setAftersale(true);

            }

            //封装到OrderListVO的handleOption
            orderListVO.setHandleOptionVO(handleOptionVO);

            orderListVOS.add(orderListVO);
        }

        PageInfo info = new PageInfo(orders);

        int total = (int) info.getTotal();
        int pages = info.getPages();
        int limit = info.getPageSize();
        int page = info.getPageNum();
    //TODO pege分页错误使用
        return new CommonData(total,pages,limit,page,orderListVOS);
    }

    @Override
    public OrderSubmitVO submit(OrderSubmitBO orderSubmitBO) {

        Order order = new Order();

        //当前时间string
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String yyyyMMdd = simpleDateFormat.format(date);

        int rs = (int) ((Math.random() * 9 + 1) * Math.pow(10, 5));
        String s = String.valueOf(rs);
        String concat = yyyyMMdd.concat(s);

        //订单编号由时间戳决定
        order.setOrderSn(concat);

        //订单状态,未付款的101
        order.setOrderStatus((short) 101);

        //售后状态0
        order.setAftersaleStatus((short) 0);

        //设置订单备注
        order.setMessage(orderSubmitBO.getMessage());

        //根据地址id查地址表
        AddressPo address = addressMapper.getAddressByAddressId(orderSubmitBO.getAddressId());

        //封装与address相关内容
        //设置电话
        order.setMobile(address.getTel());

        //收货人
        order.setConsignee(address.getName());

        String province = address.getProvince();
        String city = address.getCity();
        String county = address.getCounty();
        String allAddress = province.concat(city).concat(county);
        //地址
        order.setAddress(allAddress);

        //userId
        order.setUserId(UserInfoUtils.getUser().getId());

        //cartId为0,表示submit当前用户所有已经check的cart
        List<Cart> carts = new ArrayList<>();
        if (orderSubmitBO.getCartId() == 0){

            // 根据userId和check查询购物车表，还要排除deleted为1的
            CartExample cartExample = new CartExample();
            cartExample.createCriteria().andUserIdEqualTo(UserInfoUtils.getUser().getId()).andCheckedEqualTo(true).andDeletedEqualTo(false);
            carts = cartMapper.selectByExample(cartExample);

        }else {
            //直接购买通过cartId下单
            Cart cart = cartMapper.selectByPrimaryKey(orderSubmitBO.getCartId());
            carts.add(cart);
        }

        BigDecimal goodsPrice = new BigDecimal(0);

        //购物车总价
        for (Cart cart1 : carts) {
            goodsPrice = goodsPrice.add(cart1.getPrice().multiply(new BigDecimal(cart1.getNumber())));
        }

        //订单总价格
        order.setGoodsPrice(goodsPrice);

        //根据couponId查询优惠券表,获取优惠券信息
        MallCoupon coupon = couponMapper.selectByPrimaryKey(orderSubmitBO.getCouponId());

        BigDecimal couponZero = new BigDecimal(0);

        //使用优惠券
        if (coupon != null){

            order.setCouponPrice(coupon.getDiscount());
        }else {

            //没有优惠券,设置优惠金额为0
            order.setCouponPrice(couponZero);
        }

        //获取满减运费金额min与运费金额value
        Integer freightMin = Integer.parseInt(systemMapper.selectSystemValueByKeyName("market_express_freight_min"));
        int freightValue = Integer.parseInt(systemMapper.selectSystemValueByKeyName("market_express_freight_value"));

        //根据是否满足条件设置运费
        if (order.getGoodsPrice().intValue() >= freightMin){
            order.setFreightPrice(new BigDecimal(0));
        }else {
            order.setFreightPrice(new BigDecimal(freightValue));
        }

        //订单实际价格,商品总价格加上运费减去优惠券
        order.setOrderPrice(goodsPrice.add(order.getFreightPrice()).subtract(order.getCouponPrice()));

        //设置实付费用
        order.setActualPrice(order.getOrderPrice());

        //设置发货时间
        order.setAddTime(new Date());

        order.setIntegralPrice(new BigDecimal(0));
        order.setGrouponPrice(new BigDecimal(0));
        order.setPayId("0");
        order.setPayTime(new Date());

        //数据库插入新订单
        int row = orderMapper.insertSelective(order);

        //修改couponUser表
        if (coupon != null){

            //使用了优惠券
            //把coupon-user里的优惠券状态status改为1,要用example，UserCouponId和UserId查询
            CouponUserExample couponUserExample = new CouponUserExample();
            couponUserExample.createCriteria().andCouponIdEqualTo(orderSubmitBO.getUserCouponId()).andUserIdEqualTo(UserInfoUtils.getUser().getId());
            //找出该用户该类型的所有优惠券
            List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);

            for (CouponUser couponUser : couponUsers) {

                //选择没有使用的一个改状态即用掉
                if (couponUser.getOrderId() == null){

                    couponUser.setStatus((short) 1);
                    couponUser.setUsedTime(new Date());
                    couponUser.setOrderId(order.getId());
                    couponUser.setUpdateTime(new Date());

                    couponUserMapper.updateByPrimaryKeySelective(couponUser);

                    break;
                }

            }

        }

        //添加数据到orderGoods表
        for (Cart cart1 : carts) {

            OrderGoods orderGoods = new OrderGoods();

            orderGoods.setOrderId(order.getId());
            orderGoods.setGoodsId(cart1.getGoodsId());
            orderGoods.setGoodsName(cart1.getGoodsName());
            orderGoods.setGoodsSn(cart1.getGoodsSn());
            orderGoods.setProductId(cart1.getProductId());
            orderGoods.setNumber(cart1.getNumber());
            orderGoods.setPrice(cart1.getPrice());
            orderGoods.setSpecifications(cart1.getSpecifications());
            orderGoods.setPicUrl(cart1.getPicUrl());

            orderGoods.setComment(0);
            orderGoods.setAddTime(new Date());

            orderGoodsMapper.insertSelective(orderGoods);

        }

        //修改购物车所有信息的delete状态
        for (Cart cart2 : carts) {

            cart2.setUpdateTime(new Date());
            cart2.setDeleted(true);

            cartMapper.updateByPrimaryKey(cart2);
        }


        if (row == 1){

            OrderSubmitVO orderSubmitVO = new OrderSubmitVO(order.getId(), 0);
            return orderSubmitVO;

        }else {
        return null;
        }
    }

    @Override
    public OrderForDetailVO detail(Integer orderId) {

        Order order = orderMapper.selectByPrimaryKey(orderId);

        //封装到orderForDetailVO
        OrderForDetailVO orderForDetailVO = new OrderForDetailVO();

        //封装到orderInfo
        OrderInfoForDetailVO orderInfoForDetailVO = new OrderInfoForDetailVO();

        orderInfoForDetailVO.setConsignee(order.getConsignee());
        orderInfoForDetailVO.setAddress(order.getAddress());
        orderInfoForDetailVO.setAddTime(order.getAddTime());
        orderInfoForDetailVO.setOrderSn(order.getOrderSn());
        orderInfoForDetailVO.setActualPrice(order.getActualPrice());
        orderInfoForDetailVO.setMobile(order.getMobile());
        orderInfoForDetailVO.setMessage(order.getMessage());
        orderInfoForDetailVO.setAftersaleStatus(order.getAftersaleStatus());
        orderInfoForDetailVO.setGoodsPrice(order.getGoodsPrice());
        orderInfoForDetailVO.setCouponPrice(order.getCouponPrice());
        orderInfoForDetailVO.setId(order.getId());
        orderInfoForDetailVO.setFreightPrice(order.getFreightPrice());

        HandleOptionVO handleOptionVO = new HandleOptionVO();

        //状态不同,需要的handleoption不同
        if (order.getOrderStatus() == 101){
            orderInfoForDetailVO.setOrderStatusText("未付款");

            handleOptionVO.setCancel(true);
            handleOptionVO.setPay(true);

        }else if (order.getOrderStatus() == 102){
            orderInfoForDetailVO.setOrderStatusText("已取消");

            handleOptionVO.setDelete(true);

        }else if (order.getOrderStatus() == 103){
            orderInfoForDetailVO.setOrderStatusText("系统已取消");

            handleOptionVO.setDelete(true);

        }else if (order.getOrderStatus() == 201){
            orderInfoForDetailVO.setOrderStatusText("已付款");

            handleOptionVO.setRefund(true);

        }else if (order.getOrderStatus() == 202){
            orderInfoForDetailVO.setOrderStatusText("申请退款");

        }else if (order.getOrderStatus() == 203){
            orderInfoForDetailVO.setOrderStatusText("已退款");

        }else if (order.getOrderStatus() == 301){
            orderInfoForDetailVO.setOrderStatusText("已发货");

            handleOptionVO.setConfirm(true);

        }else if (order.getOrderStatus() == 401){
            orderInfoForDetailVO.setOrderStatusText("已收货");

           handleOptionVO.setDelete(true);
           handleOptionVO.setComment(true);
           handleOptionVO.setRebuy(true);
           handleOptionVO.setAftersale(true);

        }else if (order.getOrderStatus() == 402){
            orderInfoForDetailVO.setOrderStatusText("系统已收货");

            handleOptionVO.setDelete(true);
            handleOptionVO.setComment(true);
            handleOptionVO.setRebuy(true);
            handleOptionVO.setAftersale(true);

        }

        orderInfoForDetailVO.setHandleOption(handleOptionVO);

        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();

        orderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);

        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);

        orderForDetailVO.setOrderInfo(orderInfoForDetailVO);
        orderForDetailVO.setOrderGoods(orderGoods);

        return orderForDetailVO;

    }

    @Override
    public int orderChangeStatus(Integer orderId, int orderStatus) {

        Order order = orderMapper.selectByPrimaryKey(orderId);

        order.setOrderStatus((short) orderStatus);

        order.setUpdateTime(new Date());

        int row = orderMapper.updateByPrimaryKey(order);

        if (row == 1){
            return 200;
        }else {
            return 404;
        }
    }

    @Override
    public int orderChangeConfirmStatus(Integer orderId, int orderStatus) {

        Order order = orderMapper.selectByPrimaryKey(orderId);

        order.setOrderStatus((short) orderStatus);
        order.setUpdateTime(new Date());
        order.setConfirmTime(new Date());

        int row = orderMapper.updateByPrimaryKey(order);

        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        orderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);

        for (OrderGoods orderGood : orderGoods) {

            orderGood.setUpdateTime(new Date());

            orderGoodsMapper.updateByPrimaryKey(orderGood);
        }

        if (row == 1){
            return 200;
        }else {
            return 404;
        }

    }

    @Override
    public int orderRefund(Integer orderId, int orderStatus) {

        Order order = orderMapper.selectByPrimaryKey(orderId);

        order.setOrderStatus((short) orderStatus);
        order.setUpdateTime(new Date());
        //售后状态
        order.setAftersaleStatus((short) 1);

        int row = orderMapper.updateByPrimaryKey(order);

        //向售后表插入数据
        Aftersale aftersale = new Aftersale();


        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String yyyyMMdd = simpleDateFormat.format(date);

        int rs = (int) ((int)(Math.random() * 9 + 1) * Math.pow(10, 5));
        String s = String.valueOf(rs);
        String concat = yyyyMMdd.concat(s);

        aftersale.setAftersaleSn(concat);
        aftersale.setOrderId(order.getId());
        aftersale.setUserId(order.getUserId());
        aftersale.setType((short) 0);
        aftersale.setAmount(order.getActualPrice());
        aftersale.setStatus((short) 1);
        aftersale.setAddTime(new Date());
        aftersale.setHandleTime(new Date());
        aftersale.setUpdateTime(new Date());

        aftersaleMapper.insertSelective(aftersale);

        if (row == 1){
            return 200;
        }else {
            return 404;
        }
    }

    @Override
    public int delete(Integer orderId) {

        Order order = orderMapper.selectByPrimaryKey(orderId);

        order.setDeleted(true);
        order.setUpdateTime(new Date());

        int row = orderMapper.updateByPrimaryKey(order);

        if (row == 1){
            return 200;
        }else {
            return 404;
        }
    }

    @Override
    public OrderGoods goods(Integer orderId, Integer goodsId) {

        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        orderGoodsExample.createCriteria().andOrderIdEqualTo(orderId).andGoodsIdEqualTo(goodsId);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);

        return orderGoods.get(0);

    }

    @Override
    public int comment(CommentBO commentBO) {

        Comment comment = new Comment();

        comment.setType((byte) 0);
        comment.setContent(commentBO.getContent());
        comment.setUserId(UserInfoUtils.getUser().getId());
        comment.setPicUrls(commentBO.getPicUrls());

        if (commentBO.getPicUrls() == null){
            comment.setHasPicture(false);
        }else {
            comment.setHasPicture(true);
        }

        comment.setStar(commentBO.getStar());
        comment.setAddTime(new Date());
        comment.setUpdateTime(new Date());

        OrderGoods orderGoods = orderGoodsMapper.selectByPrimaryKey(commentBO.getOrderGoodsId());

        System.out.println(orderGoods);

        comment.setValueId(orderGoods.getGoodsId());

        int row = commentMapper.insertSelective(comment);

        if (row == 1){

            orderGoods.setComment(comment.getId());
            orderGoods.setUpdateTime(new Date());

            orderGoodsMapper.updateByPrimaryKeySelective(orderGoods);

            return 200;
        }else {
            return 404;
        }
    }


}
